package biz

import (
	"context"
	"time"

	"lianzi_gos/internal/mods/mpweixin/dal"
	"lianzi_gos/internal/mods/mpweixin/schema"
	"lianzi_gos/pkg/errors"
	"lianzi_gos/pkg/util"
)

// 收藏表
type Collect struct {
	Trans      *util.Trans
	CollectDAL *dal.Collect
}

// Query collects from the data access object based on the provided parameters and options.
func (a *Collect) Query(ctx context.Context, params schema.CollectQueryParam) (*schema.CollectQueryResult, error) {
	params.Pagination = true
	params.UID = util.FromUserID(ctx)
	result, err := a.CollectDAL.Query(ctx, params, schema.CollectQueryOptions{
		QueryOptions: util.QueryOptions{
			OrderFields: []util.OrderByParam{},
		},
	})
	if err != nil {
		return nil, err
	}
	return result, nil
}

// Get the specified collect from the data access object.
func (a *Collect) Get(ctx context.Context, id string) (*schema.Collect, error) {
	collect, err := a.CollectDAL.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if collect == nil {
		return nil, errors.NotFound("", "Collect not found")
	}
	return collect, nil
}

// Create a new collect in the data access object.
func (a *Collect) Create(ctx context.Context, formItem *schema.CollectForm) (*schema.Collect, error) {
	collect := &schema.Collect{
		ID:        util.NewXID(),
		CreatedAt: time.Now(),
	}
	collect.UID = util.FromUserID(ctx)
	if err := formItem.FillTo(collect); err != nil {
		return nil, err
	}

	err := a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.CollectDAL.Create(ctx, collect); err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return collect, nil
}

// Update the specified collect in the data access object.
func (a *Collect) Update(ctx context.Context, id string, formItem *schema.CollectForm) error {
	collect, err := a.CollectDAL.Get(ctx, id)
	if err != nil {
		return err
	} else if collect == nil {
		return errors.NotFound("", "Collect not found")
	}

	if err := formItem.FillTo(collect); err != nil {
		return err
	}
	collect.UpdatedAt = time.Now()

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.CollectDAL.Update(ctx, collect); err != nil {
			return err
		}
		return nil
	})
}

// Delete the specified collect from the data access object.
func (a *Collect) Delete(ctx context.Context, id string) error {
	//exists, err := a.CollectDAL.Exists(ctx, id)
	//if err != nil {
	//	return err
	//} else if !exists {
	//	return errors.NotFound("", "Collect not found")
	//}
	uid := util.FromUserID(ctx)
	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.CollectDAL.Delete(ctx, id, uid); err != nil {
			return err
		}
		return nil
	})
}
